<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card >
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showAddDialog">添加分类</el-button>
                </el-col>
                <!-- 树形表格 -->
                <tree-table :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index border class="treeTable">
                    <!-- 是否有效 -->
                    <template slot="isOk" slot-scope="scope">
                        <i class="el-icon-error" style="color:red" v-if="scope.row.cate_deleted"></i>
                        <i class="el-icon-success" style="color:lightgreen" v-else></i>
                    </template>
                    <!-- 排序 -->
                    <template slot="order" slot-scope="scope">
                        <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
                        <el-tag size="mini" type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
                        <el-tag size="mini" type="warning" v-else>三级</el-tag>
                    </template>
                    <!-- 操作 -->
                    <template slot="operate" slot-scope="scope">
                        <el-button size="mini" type="primary" class="el-icon-edit" @click="selectSort(scope.row.cat_id)">编辑</el-button>
                        <el-button size="mini" type="danger" class="el-icon-delete" @click="removeGoodsById(scope.row,scope.row.cat_id)">删除</el-button>
                    </template>
                </tree-table>
                <!-- 分页 -->
                <el-pagination
                    :page-sizes="[3,5,10,15]"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                >
                </el-pagination>
            </el-row>
            <!-- 修改分类 -->
            <el-dialog
                title="修改分类"
                :visible.sync="modifyVisible"
                @close="outModify"
            >
                <el-form
                    :model="modifyForm"
                    :rules="addFormrules"
                    label-width="80px"
                    ref="modifySortRef"
                >
                    <el-form-item label="分类名称" prop="cat_name" >
                        <el-input v-model="modifyForm.cat_name" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
				    <el-button @click="modifyVisible = false">取 消</el-button>
				    <el-button type="primary" @click="modifySortInfo">确 定</el-button>
			    </div>
            </el-dialog>
        <!-- 添加分类 -->
            <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" >
                <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" >
                    <el-form-item label="分类名称" prop="cat_name" label-width="100px">
                        <el-input v-model="addForm.cat_name" ></el-input>
                    </el-form-item>
                    <el-form-item label="父级分类" label-width="100px">
                        <el-cascader
                            v-model="selectedKeys"
                            :options="parentCateList"
                            :props="cascaderProps"
                            clearable
                        ></el-cascader>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addCate">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
export default {
    data(){
        return{
            queryInfo:{
                type:3,
                pagenum:1,
                pagesize:5
            },
            cateList:[],
            total:0,
            columns:[
                {
                    label:'分类名称',
                    prop:'cat_name'
                },
                {
                    label:'是否有效',
                    type:'template',
                    template:'isOk'
                },
                {
                    label:'排序',
                    type:'template',
                    template:'order'
                },
                {
                    label:'操作',
                    type:'template',
                    template:'operate'
                },

            ],
            addDialogVisible: false,
            addForm:{
                cat_name: "", // 分类名称
                cat_pid:0,  // 父级分类的id
                cat_level:0 // 分类的等级
            },
            addFormrules: {
                cat_name: [
                    {
                        required: true,
                        message: "请输入分类名称",
                        trigger: "blur",
                    },
                    {
                        min: 3,
                        max: 8,
                        message: "长度在 3 到 8 个字符",
                        trigger: "blur",
                    },
                ],
            },
            parentCateList:[],
            cascaderProps:{
                expandTrigger:'hover',
                label:'cat_name',
                value:'cat_id',
                children:'children',
                checkStrictly:true
            },
            // 级联选择器选中的id数组
            selectedKeys:[],
            //修改
            modifyForm:{},
            modifyVisible:false,
        }
    },
    created() {
        this.getCateList();
    },
    methods: {
        async getCateList(){
            const { data: res } = await this.$http.get('categories',{
                params:this.queryInfo
            })
            console.log(res)
            if(res.meta.status != 200){
               return this.$message.error("获取分类列表失败")
            }
            this.cateList=res.data.result
            this.total=res.data.total
            console.log(this.cateList);
        },
        //分页
        handleSizeChange(val) {
            this.queryInfo.pagesize = val
            this.getCateList()
        },
        handleCurrentChange(val) {
            this.queryInfo.pagenum = val
             this.getCateList()
        },
        //根据id删除商品
        removeGoodsById(cate,id){
            this.$confirm("确定要删除该商品吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    const { data: res } = await this.$http.delete(
                        `categories/${id}`
                    );
                    if (res.meta.status != 200) {
                        return this.$message.error("删除权限失败");
                    }
                    cate.result=res.data;
                    this.$message.success("删除成功!");
                })
                .catch(() => {
                    this.$message.info("已取消删除!");
                });
        },
        // 添加分类
        showAddDialog(){
            this.addDialogVisible=true,
            this.getParentCateList()
        },
        async getParentCateList(){
            const {data:res} = await this.$http.get('categories',{
                params:{type:2}
            })
            this.parentCateList = res.data
            console.log(this.parentCateList);
        },
        addCate(){
            this.$refs.addFormRef.validate( async valid =>{
                if(!valid){
                    return
                }
                //判断是否选择了父级分类
                if(this.selectedKeys.length>0){
                    // 父级分类的id
                    this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length-1]
                    // 分类的等级
                    this.addForm.cat_level = this.selectedKeys.length
                } 

                const {data:res} = await this.$http.post('categories',this.addForm)
                if(res.meta.status != 201){
                    return this.$message.error('添加分类失败')
                }

                this.$message.success('添加分类成功')
                this.getCateList()
                this.addDialogVisible = false
            })
        },
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
            this.selectedKeys = []
            this.addForm.cat_pid = 0
            this.addForm.cat_level = 0
        },
        //修改分类
        async selectSort(id){
            const { data: res } = await this.$http.get("categories/"+id)
            if(res.meta.status != 200){
                return this.$message.error("查询用户信息失败")
            }
            this.modifyForm=res.data;
            this.modifyVisible=true;
        },
        // 监听修改用户对话框的关闭事件
        outModify () {
            this.$refs.modifySortRef.resetFields()
        },
        modifySortInfo(){
            this.$refs.modifySortRef.validate(async valid => {
                //判断状态
                if(!valid){
                    return this.$message.error('修改用户信息失败');
                }
                //发起修改用户请求
                const { data: res } = await this.$http.put('categories/' + this.modifyForm.cat_id, {
                    cat_name:this.modifyForm.cat_name,
                    
                })
                // 判断数据是否请求到
                if (res.meta.status !== 200) {
                    return this.$message.error('修改用户信息失败');
                }
                this.$message.success('修改用户信息成功');
                // 关闭对话框
                this.modifyVisible = false;
                this.getCateList();
            })
        }
    }
}
</script>
<style lang="less">
.treeTable {
    margin-top:15px;
}
.el-cascader{
    width: 100%;
}
</style>